//
//  WelcomeViewController.swift
//  SinaWebo
//
//  Created by mis on 16/3/19.
//  Copyright © 2016年 mis. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage

class WelcomeViewController: UIViewController {

    override func loadView() {
        view = backImage
    }
    
    private func setupUI() {
        view.addSubview(iconImage)
        view.addSubview(wecomeLabel)
        
        iconImage.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(view.snp_centerX)
            make.height.equalTo(90)
            make.width.equalTo(90)
            make.bottom.equalTo(view.snp_bottom).offset(-180)
            print(view.snp_bottom)
        }
        
        wecomeLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(iconImage.snp_bottom).offset(20)
            make.centerX.equalTo(view.snp_centerX)
        }
        
        // 第三方框架 异步加载头像图片
        iconImage.sd_setImageWithURL(UserAccountViewModel().headURL, placeholderImage: UIImage(named: "avatar_default_big"))
        iconImage.layer.cornerRadius = 45
        iconImage.layer.masksToBounds = true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        startAnimation()
    }
    
    private func startAnimation() {
        self.iconImage.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(self.view.snp_bottom).offset(-self.view.bounds.size.height + 180)
        }
        self.wecomeLabel.alpha = 0
        UIView.animateWithDuration(1.2, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 9.8, options: [], animations: { () -> Void in
            self.view.layoutIfNeeded()
            }) { (_) -> Void in
                UIView.animateWithDuration(0.6, animations: { () -> Void in
                    self.wecomeLabel.alpha = 1
                    }, completion: { (_) -> Void in
                        NSNotificationCenter.defaultCenter().postNotificationName(AppSwitchRootViewControler, object: nil)
                })
        }
    }
    
    private lazy var backImage: UIImageView = UIImageView(image: UIImage(named: "ad_background"))
    
    private lazy var wecomeLabel: UILabel = {
        let lbl = UILabel()
        lbl.font = UIFont.systemFontOfSize(19)
        lbl.textColor = UIColor.lightGrayColor()
        lbl.textAlignment = .Center
        lbl.text = (UserAccountViewModel().name ?? "") + ",欢迎回来!"
        lbl.alpha = 0
        lbl.sizeToFit()
        return lbl
    }()
    
    private lazy var iconImage: UIImageView = UIImageView()

}
